package com.huiztech.kaoqinji.mvc;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.huiztech.common.http.HuizBaseJsonResponseHandler;
import com.huiztech.common.http.HuizBaseJsonResponseHandler.Callback;
import com.huiztech.common.sample.SampleController.User;
import com.huiztech.kaoqinji.AppConst;
import com.huiztech.kaoqinji.LocApplication;
import com.huiztech.kaoqinji.MainActivity;
import com.huiztech.kaoqinji.MainTabActivity;
import com.huiztech.kaoqinji.R;
import com.huiztech.kaoqinji.model.AddClient;
import com.huiztech.kaoqinji.model.AttendanceData;
import com.huiztech.kaoqinji.model.ClientData;
import com.huiztech.kaoqinji.model.ClientDetail;
import com.huiztech.kaoqinji.model.Interval;
import com.huiztech.kaoqinji.model.IntervalData;
import com.huiztech.kaoqinji.model.Login;
import com.huiztech.kaoqinji.model.Remark;
import com.huiztech.kaoqinji.model.SignOn;
import com.huiztech.kaoqinji.model.UserInfo;
import com.huiztech.kaoqinji.model.UserInfoDetail;
import com.huiztech.kaoqinji.service.LocationService;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;
import com.loopj.android.http.RequestParams;

public class KaoqinController extends AbstractKaoqinController {

    private Gson gson = new Gson();

    @Override
    public void doLogin(final String username, final String password) {
        RequestParams params = new RequestParams();
        params.put("username", username);
        params.put("password", password);
        params.put("for_login", "1");

        this.httpClient.post(AppConst.KAOQIN_LOGIN_URL, params, new HuizBaseJsonResponseHandler<Login>(this, true,
                false) {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Login response) {
                if (response.getState() == AppConst.STATE_FAILURE) {
                    huizView.hideBusy();
                    huizView.showMessage(response.getMsg());
                } else {
                    UserInfo userInfo = response.getData();
                    UserInfoDetail userInfoDetail = userInfo.getCompanyStaff();
                    userInfoDetail.setUsername(username);
                    userInfoDetail.setPassword(password);
                    storeUserToLocal(userInfoDetail);
                    huizView.showMessage(R.string.LoginSuccess);
                    getInterval();
                }
            }

            @Override
            protected Login parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                Login login = gson.fromJson(rawJsonData, Login.class);
                return login;
            }
        });

    }

    @Override
    public void doSignOn(double lat, double lng, final Callback<SignOn> callback) {
        RequestParams params = new RequestParams();
        UserInfoDetail userInfoDetail = getUserFromModel();
        params.put("username", userInfoDetail.getUsername());
        params.put("password", userInfoDetail.getPassword());
        params.put("type", "1"); //[1:签到签退 2:客户拜访]
        params.put("customer_id", "");// 客户id 签到时不需要填写
        params.put("create_type", "1"); //[1:手动 2:自动]
        params.put("lng", String.valueOf(lng));
        params.put("lat", String.valueOf(lat));
        params.put("start_time", String.valueOf(System.currentTimeMillis() / 1000));
        //TODO： 采集时间：采集地理信息时间  将来需要在无网络情况下存储在信息里
        params.put("acquisition_time", String.valueOf(System.currentTimeMillis() / 1000));

        this.httpClient.post(AppConst.KAOQIN_SIGNON_URL, params, new HuizBaseJsonResponseHandler<SignOn>(this) {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SignOn response) {
                LogUtils.i(rawJsonResponse);
                if (response.getState() == AppConst.STATE_SUCCESS) {
                    AttendanceData data = response.getData();
                    putInfoFromLocal(AppConst.SP_ATTENDANCE_KEY, data.getAttendanceId());
                    huizView.showMessage(R.string.SignOnSuccess);
                    context.startService(new Intent(context, LocationService.class));
                } else {
                    huizView.showMessage(R.string.SignOnFailure);
                }
                if (callback != null) {
                    callback.execute(response);
                }
            }

            @Override
            protected SignOn parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                LogUtils.i(rawJsonData);
                SignOn sign = gson.fromJson(rawJsonData, SignOn.class);
                return sign;
            }
        });
    }

    @Override
    public void doSignOut(double lat, double lng, final Callback<SignOn> callback) {
        UserInfoDetail userInfoDetail = getUserFromModel();
        RequestParams params = new RequestParams();
        params.put("username", userInfoDetail.getUsername());
        params.put("password", userInfoDetail.getPassword());
        params.put("attendance_id", getInfoByLocal(AppConst.SP_ATTENDANCE_KEY, ""));
        params.put("lat", String.valueOf(lat));
        params.put("lng", String.valueOf(lng));
        params.put("end_time", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("acquisition_time", String.valueOf(System.currentTimeMillis() / 1000));

        this.httpClient.post(AppConst.KAOQIN_SIGNOUT_URL, params, new HuizBaseJsonResponseHandler<SignOn>(this) {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SignOn response) {
                LogUtils.i(rawJsonResponse);
                if (response.getState() == AppConst.STATE_SUCCESS) {
                    huizView.showMessage(R.string.SignOutSuccess);
                    context.stopService(new Intent(context, LocationService.class));
                    removeInfoFromLocal(AppConst.SP_ATTENDANCE_KEY);
                } else {
                    huizView.showMessage(R.string.SignOutFailure);
                }

                if (callback != null) {
                    callback.execute(response);
                }
            }

            @Override
            protected SignOn parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                LogUtils.i(rawJsonData);
                SignOn sign = gson.fromJson(rawJsonData, SignOn.class);
                return sign;
            }
        });
    }

    @Override
    public void doVisitServer(double lat, double lng) {
        RequestParams params = new RequestParams();
        params.put("username", getInfoByLocal("username", ""));
        params.put("password", getInfoByLocal("password", ""));
        params.put("attendance_id", getInfoByLocal(AppConst.SP_ATTENDANCE_KEY, ""));
        params.put("lat", String.valueOf(lat));
        params.put("lng", String.valueOf(lng));
        params.put("acquisition_time", String.valueOf(System.currentTimeMillis() / 1000));
        this.httpClient.post(AppConst.KAOQIN_VISIT_SERVER_URL, params, new HuizBaseJsonResponseHandler<SignOn>(this,
                false, false) {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SignOn response) {
                int state = response.getState();
                if (state == AppConst.STATE_SUCCESS) {
                    Log.i("service", "发送成功！");
                } else {
                    Log.i("service", "发送失败！");
                }
            }

            @Override
            protected SignOn parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                SignOn sign = gson.fromJson(rawJsonData, SignOn.class);
                return sign;
            }
        });

    }

    @Override
    public void getCustomerData(String ForNearBy,double lat,double lng, final Callback<ClientData> callback) {
        RequestParams params = new RequestParams();
        UserInfoDetail userInfoDetail = getUserFromModel();
        params.put("username", userInfoDetail.getUsername());
        params.put("password", userInfoDetail.getPassword());
        params.put("lat", String.valueOf(lat));
        params.put("lng", String.valueOf(lng));
        this.httpClient.post(AppConst.KAOQIN_GET_CLIENT_URL, params, new HuizBaseJsonResponseHandler<ClientData>(this) {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, ClientData response) {
                int state = response.getState();
                if (state == AppConst.STATE_SUCCESS) {
                    List<ClientDetail> clientDetail = response.getData();
                    huizModel.put("clientDetail", clientDetail);
                } else {
                    huizView.showMessage(R.string.GetCustomerFailure);
                }

                if (callback != null && response.getData() != null) {
                    callback.execute(response);
                }

            }

            @Override
            protected ClientData parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                ClientData cd = gson.fromJson(rawJsonData, ClientData.class);
                return cd;
            }
        });

    }

    @Override
    public void addCustomer(String companyName, String companyAddress, String name, File file, String position,
            String phone, String email, String qq) {
        RequestParams params = new RequestParams();
        UserInfoDetail userInfoDetail = getUserFromModel();
        params.put("username", userInfoDetail.getUsername());
        params.put("password", userInfoDetail.getPassword());
        params.put("company_name", companyName);
        params.put("company_address", companyAddress);
        params.put("name", name);
        try {
            params.put("file", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        params.put("position", position);
        params.put("phone", phone);
        params.put("email", email);
        params.put("qq", qq);

        this.httpClient.post(AppConst.KAOQIN_ADD_CLIENT_URL, params, new HuizBaseJsonResponseHandler<AddClient>(this) {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, AddClient response) {
                int state = response.getState();
                if (state == AppConst.STATE_SUCCESS) {
                    huizView.showMessage(R.string.AddClientSuccess);
                } else {
                    huizView.showMessage(R.string.AddClientFailure);
                }
                ((Activity) context).finish();
            }

            @Override
            protected AddClient parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                AddClient addClient = gson.fromJson(rawJsonData, AddClient.class);
                return addClient;
            }
        });
    }

    @SuppressWarnings("null")
    @Override
    public void startVisit(double lat, double lng, final int customerId, File file) {
        RequestParams params = new RequestParams();
        UserInfoDetail userInfoDetail = getUserFromModel();
        params.put("username", userInfoDetail.getUsername());
        params.put("password", userInfoDetail.getPassword());
        params.put("attendance_pid", getInfoByLocal(AppConst.SP_ATTENDANCE_KEY, ""));
        params.put("start_time", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("type", "2");
        params.put("customer_id", String.valueOf(customerId));
        params.put("create_type", "");//1.手动,2.自动
        try {
            params.put("file", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        params.put("lng", String.valueOf(lng));
        params.put("lat", String.valueOf(lat));
        params.put("acquisition_time", String.valueOf(System.currentTimeMillis() / 1000));

        this.httpClient.post(AppConst.KAOQIN_SIGNON_URL, params, new HuizBaseJsonResponseHandler<SignOn>(this) {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SignOn response) {
                LogUtils.i(rawJsonResponse);
                int state = response.getState();
                if (state == AppConst.STATE_SUCCESS) {
                    AttendanceData data = response.getData();
                    editor.putString(AppConst.SP_VISIT_KEY, data.getAttendanceId());
                    editor.putInt(AppConst.SP_CUSTOMER_ID_KEY, customerId);
                    huizView.showMessage(R.string.StartVisitSuccess);
                    editor.putString(AppConst.SP_MAP_POP_TEXT, "正在拜访...");
                    editor.commit();
                } else {
                    huizView.showMessage(R.string.StartVisitFailure);
                }
            }

            @Override
            protected SignOn parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                SignOn sign = gson.fromJson(rawJsonData, SignOn.class);
                return sign;
            }
        });
    }

    @Override
    public void stopVisit(double lat, double lng, int customerId) {
        RequestParams params = new RequestParams();
        UserInfoDetail userInfoDetail = getUserFromModel();
        params.put("username", userInfoDetail.getUsername());
        params.put("password", userInfoDetail.getPassword());
        params.put("attendance_id", getInfoByLocal(AppConst.SP_VISIT_KEY, ""));
        params.put("lat", String.valueOf(lat));
        params.put("lng", String.valueOf(lng));
        params.put("end_time", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("acquisition_time", String.valueOf(System.currentTimeMillis() / 1000));
        this.httpClient.post(AppConst.KAOQIN_SIGNOUT_URL, params, new HuizBaseJsonResponseHandler<SignOn>(this) {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SignOn response) {
                int state = response.getState();
                if (state == AppConst.STATE_SUCCESS) {
                    editor.remove(AppConst.SP_CUSTOMER_ID_KEY);
                    huizView.showMessage(R.string.StopVisitSuccess);
                    editor.putString(AppConst.SP_MAP_POP_TEXT, "我在这里...");
                    editor.remove("visit_time");
                    editor.remove("visit_btn");
                    editor.commit();
                } else {
                    huizView.showMessage(R.string.StopVisitFailure);
                }
            }

            @Override
            protected SignOn parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                SignOn sign = gson.fromJson(rawJsonData, SignOn.class);
                return sign;
            }
        });
    }

    @Override
    public void getInterval() {
        RequestParams params = new RequestParams();
        UserInfoDetail userInfoDetail = getUserFromModel();
        params.put("username", userInfoDetail.getUsername());
        params.put("password", userInfoDetail.getPassword());

        this.httpClient.post(AppConst.KAOQIN_GET_INTERVAL, params, new HuizBaseJsonResponseHandler<IntervalData>(this,
                false, true) {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, IntervalData response) {
                int state = response.getState();
                if (state == AppConst.STATE_SUCCESS) {
                    Interval interval = response.getData();
                    putInfoFromLocal("interval", interval.getAcquisitionInterval());
                    //                    huizModel.put("interval", interval.getAcquisitionInterval());
                } else {
                    putInfoFromLocal("interval", AppConst.MOREN_INTERVAL);
                }
                Intent intent = new Intent(context, MainTabActivity.class);
                context.startActivity(intent);
                ((Activity) context).finish();
            }

            @Override
            protected IntervalData parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                IntervalData intervalData = gson.fromJson(rawJsonData, IntervalData.class);
                return intervalData;
            }
        });
    }

    @Override
    public void storeRemarkToDB(Remark remark) {
        try {
            LogUtils.i(LocApplication.db + "==");
            LocApplication.db.saveOrUpdate(remark);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Remark> getRemarksFromDB() {
        List<Remark> remarks = new ArrayList<Remark>();
        try {
            remarks = LocApplication.db.findAll(Selector.from(Remark.class).orderBy("storeTime", true));
        } catch (DbException e) {
            e.printStackTrace();
        }
        return remarks;

    }

    @Override
    public void delRemarkFromDbById(int id) {
        try {
            LocApplication.db.deleteById(Remark.class, id);
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

}
